<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/网络编程/9-解决粘包问题 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/网络编程/9-解决粘包问题</h2>



  <p class="post-date">2020-10-17</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="一、解决粘包问题-low版"><a href="#一、解决粘包问题-low版" class="headerlink" title="一、解决粘包问题(low版)"></a>一、解决粘包问题(low版)</h1><p>问题的根源在于，接收端不知道发送端将要传送的字节流的长度，所以解决粘包的方法就是围绕，如何让发送端在发送数据前，把自己将要发送的字节流总大小让接收端知晓，然后接收端来一个死循环接收完所有数据。</p>
<h2 id="1-1-服务端"><a href="#1-1-服务端" class="headerlink" title="1.1 服务端"></a>1.1 服务端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> socket, subprocess</span><br><span class="line"></span><br><span class="line">server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</span><br><span class="line"></span><br><span class="line">server.bind((<span class="string">'127.0.0.1'</span>, <span class="number">8000</span>))</span><br><span class="line">server.listen(<span class="number">5</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    conn, addr = server.accept()</span><br><span class="line"></span><br><span class="line">    print(<span class="string">'start...'</span>)</span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        cmd = conn.recv(<span class="number">1024</span>)</span><br><span class="line">        print(<span class="string">'cmd:'</span>, cmd)</span><br><span class="line"></span><br><span class="line">        obj = subprocess.Popen(cmd.decode(<span class="string">'utf8'</span>),</span><br><span class="line">                               shell=<span class="literal">True</span>,</span><br><span class="line">                               stderr=subprocess.PIPE,</span><br><span class="line">                               stdout=subprocess.PIPE)</span><br><span class="line"></span><br><span class="line">        stdout = obj.stdout.read()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> stdout:</span><br><span class="line">            ret = stdout</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            stderr = obj.stderr.read()</span><br><span class="line">            ret = stderr</span><br><span class="line"></span><br><span class="line">        ret_len = len(ret)</span><br><span class="line"></span><br><span class="line">        conn.send(str(ret_len).encode(<span class="string">'utf8'</span>))</span><br><span class="line"></span><br><span class="line">        data = conn.recv(<span class="number">1024</span>).decode(<span class="string">'utf8'</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> data == <span class="string">'recv_ready'</span>:</span><br><span class="line">            conn.sendall(ret)</span><br><span class="line"></span><br><span class="line">    conn.close()</span><br><span class="line"></span><br><span class="line">server.close()</span><br></pre></td></tr></table></figure>

<h2 id="1-2-客户端"><a href="#1-2-客户端" class="headerlink" title="1.2 客户端"></a>1.2 客户端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> socket</span><br><span class="line"></span><br><span class="line">client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</span><br><span class="line"></span><br><span class="line">client.connect((<span class="string">'127.0.0.1'</span>, <span class="number">8000</span>))</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    msg = input(<span class="string">'please enter your cmd you want&gt;&gt;&gt;'</span>).strip()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> len(msg) == <span class="number">0</span>: <span class="keyword">continue</span></span><br><span class="line"></span><br><span class="line">    client.send(msg.encode(<span class="string">'utf8'</span>))</span><br><span class="line">    length = int(client.recv(<span class="number">1024</span>))</span><br><span class="line"></span><br><span class="line">    client.send(<span class="string">'recv_ready'</span>.encode(<span class="string">'utf8'</span>))</span><br><span class="line"></span><br><span class="line">    send_size = <span class="number">0</span></span><br><span class="line">    recv_size = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    data = <span class="string">b''</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> recv_size &lt; length:</span><br><span class="line">        data = client.recv(<span class="number">1024</span>)</span><br><span class="line">        recv_size += len(data)</span><br><span class="line"></span><br><span class="line">    print(data.decode(<span class="string">'utf8'</span>))</span><br></pre></td></tr></table></figure>

<h2 id="1-3-为何low"><a href="#1-3-为何low" class="headerlink" title="1.3 为何low"></a>1.3 为何low</h2><p>程序的运行速度远快于网络传输速度，所以在发送一段字节前，先用send去发送该字节流长度，这种方式会放大网络延迟带来的性能损耗</p>
<h1 id="二、补充struct模块"><a href="#二、补充struct模块" class="headerlink" title="二、补充struct模块"></a>二、补充struct模块</h1><h2 id="2-1-简单使用"><a href="#2-1-简单使用" class="headerlink" title="2.1 简单使用"></a>2.1 简单使用</h2><p><img src="https://tva1.sinaimg.cn/large/007S8ZIlly1gjrnbe0gaaj30hm0b1dim.jpg" alt="124-解决粘包问题-struct模块参数.png?x-oss-process=style/watermark"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> struct</span><br><span class="line"><span class="keyword">import</span> json</span><br><span class="line"></span><br><span class="line"><span class="comment"># 'i'是格式</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    obj = struct.pack(<span class="string">'i'</span>, <span class="number">1222222222223</span>)</span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">    print(e)</span><br><span class="line">    obj = struct.pack(<span class="string">'i'</span>, <span class="number">1222</span>)</span><br><span class="line">print(obj, len(obj))</span><br><span class="line"><span class="string">'i'</span> format requires <span class="number">-2147483648</span> &lt;= number &lt;= <span class="number">2147483647</span></span><br><span class="line"><span class="string">b'\xc6\x04\x00\x00'</span> <span class="number">4</span></span><br><span class="line">res = struct.unpack(<span class="string">'i'</span>, obj)</span><br><span class="line">print(res[<span class="number">0</span>])</span><br><span class="line"><span class="number">1222</span></span><br></pre></td></tr></table></figure>

<h1 id="三、解决粘包问题"><a href="#三、解决粘包问题" class="headerlink" title="三、解决粘包问题"></a>三、解决粘包问题</h1><p>解决粘包问题的核心就是：为字节流加上自定义固定长度报头，报头中包含字节流长度，然后一次send到对端，对端在接收时，先从缓存中取出定长的报头，然后再取真实数据。</p>
<h2 id="3-1-使用struct模块创建报头"><a href="#3-1-使用struct模块创建报头" class="headerlink" title="3.1 使用struct模块创建报头"></a>3.1 使用struct模块创建报头</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="keyword">import</span> struct</span><br><span class="line"></span><br><span class="line">header_dic = &#123;</span><br><span class="line">    <span class="string">'filename'</span>: <span class="string">'a.txt'</span>,</span><br><span class="line">    <span class="string">'total_size'</span>:</span><br><span class="line">    <span class="number">111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222223131232</span>,</span><br><span class="line">    <span class="string">'hash'</span>: <span class="string">'asdf123123x123213x'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">header_json = json.dumps(header_dic)</span><br><span class="line"></span><br><span class="line">header_bytes = header_json.encode(<span class="string">'utf-8'</span>)</span><br><span class="line">print(len(header_bytes))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 'i'是格式</span></span><br><span class="line">obj = struct.pack(<span class="string">'i'</span>, len(header_bytes))</span><br><span class="line">print(obj, len(obj))</span><br><span class="line"><span class="number">223</span></span><br><span class="line"><span class="string">b'\xdf\x00\x00\x00'</span> <span class="number">4</span></span><br><span class="line">res = struct.unpack(<span class="string">'i'</span>, obj)</span><br><span class="line">print(res[<span class="number">0</span>])</span><br><span class="line"><span class="number">223</span></span><br></pre></td></tr></table></figure>

<h2 id="3-2-服务端"><a href="#3-2-服务端" class="headerlink" title="3.2 服务端"></a>3.2 服务端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> socket <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">import</span> subprocess</span><br><span class="line"><span class="keyword">import</span> struct</span><br><span class="line"><span class="keyword">import</span> json</span><br><span class="line"></span><br><span class="line">server = socket(AF_INET, SOCK_STREAM)</span><br><span class="line">server.bind((<span class="string">'127.0.0.1'</span>, <span class="number">8000</span>))</span><br><span class="line">server.listen(<span class="number">5</span>)</span><br><span class="line"></span><br><span class="line">print(<span class="string">'start...'</span>)</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    conn, client_addr = server.accept()</span><br><span class="line">    print(conn, client_addr)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        cmd = conn.recv(<span class="number">1024</span>)</span><br><span class="line"></span><br><span class="line">        obj = subprocess.Popen(cmd.decode(<span class="string">'utf8'</span>),</span><br><span class="line">                               shell=<span class="literal">True</span>,</span><br><span class="line">                               stderr=subprocess.PIPE,</span><br><span class="line">                               stdout=subprocess.PIPE)</span><br><span class="line"></span><br><span class="line">        stderr = obj.stderr.read()</span><br><span class="line">        stdout = obj.stdout.read()</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 制作报头</span></span><br><span class="line">        header_dict = &#123;</span><br><span class="line">            <span class="string">'filename'</span>: <span class="string">'a.txt'</span>,</span><br><span class="line">            <span class="string">'total_size'</span>: len(stdout) + len(stderr),</span><br><span class="line">            <span class="string">'hash'</span>: <span class="string">'xasf123213123'</span></span><br><span class="line">        &#125;</span><br><span class="line">        header_json = json.dumps(header_dict)</span><br><span class="line">        header_bytes = header_json.encode(<span class="string">'utf8'</span>)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 1. 先把报头的长度len(header_bytes)打包成4个bytes，然后发送</span></span><br><span class="line">        conn.send(struct.pack(<span class="string">'i'</span>, len(header_bytes)))</span><br><span class="line">        <span class="comment"># 2. 发送报头</span></span><br><span class="line">        conn.send(header_bytes)</span><br><span class="line">        <span class="comment"># 3. 发送真实的数据</span></span><br><span class="line">        conn.send(stdout)</span><br><span class="line">        conn.send(stderr)</span><br><span class="line"></span><br><span class="line">    conn.close()</span><br><span class="line"></span><br><span class="line">server.close()</span><br></pre></td></tr></table></figure>

<h2 id="3-3-客户端"><a href="#3-3-客户端" class="headerlink" title="3.3 客户端"></a>3.3 客户端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> socket <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="keyword">import</span> struct</span><br><span class="line"></span><br><span class="line">client = socket(AF_INET, SOCK_STREAM)</span><br><span class="line">client.connect((<span class="string">'127.0.0.1'</span>, <span class="number">8000</span>))</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    cmd = input(<span class="string">'please enter your cmd you want&gt;&gt;&gt;'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> len(cmd) == <span class="number">0</span>: <span class="keyword">continue</span></span><br><span class="line"></span><br><span class="line">    client.send(cmd.encode(<span class="string">'utf8'</span>))</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 1. 先收4个字节，这4个字节中包含报头的长度</span></span><br><span class="line">    header_len = struct.unpack(<span class="string">'i'</span>, client.recv(<span class="number">4</span>))[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 2. 再接收报头</span></span><br><span class="line">    header_bytes = client.recv(header_len)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 3. 从包头中解析出想要的东西</span></span><br><span class="line">    header_json = header_bytes.decode(<span class="string">'utf8'</span>)</span><br><span class="line">    header_dict = json.loads(header_json)</span><br><span class="line">    total_size = header_dict[<span class="string">'total_size'</span>]</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 4. 再收真实的数据</span></span><br><span class="line">    recv_size = <span class="number">0</span></span><br><span class="line">    res = <span class="string">b''</span></span><br><span class="line">    <span class="keyword">while</span> recv_size &lt; total_size:</span><br><span class="line">        data = client.recv(<span class="number">1024</span>)</span><br><span class="line"></span><br><span class="line">        res += data</span><br><span class="line">        recv_size += len(data)</span><br><span class="line"></span><br><span class="line">    print(res.decode(<span class="string">'utf8'</span>))</span><br><span class="line"></span><br><span class="line">client.close()</span><br></pre></td></tr></table></figure>

<h1 id="四、TCP协议粘包问题分析"><a href="#四、TCP协议粘包问题分析" class="headerlink" title="四、TCP协议粘包问题分析"></a>四、TCP协议粘包问题分析</h1><p>1.nagle算法规定，TCP协议会将数据量较小、时间间隔短的数据合并为一条发送给客户端</p>
<h2 id="4-1-服务端"><a href="#4-1-服务端" class="headerlink" title="4.1 服务端"></a>4.1 服务端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> socket <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">server = socket(AF_INET, SOCK_STREAM)</span><br><span class="line">server.bind((<span class="string">'127.0.0.1'</span>, <span class="number">8080</span>))</span><br><span class="line">server.listen(<span class="number">5</span>)</span><br><span class="line"></span><br><span class="line">conn, addr = server.accept()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 正确做法，客户端制作报头</span></span><br><span class="line"><span class="comment"># res1 = conn.recv(5)</span></span><br><span class="line"><span class="comment"># print('第一次；', res1)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># res2 = conn.recv(5)</span></span><br><span class="line"><span class="comment"># print('第二次；', res2)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># res3 = conn.recv(4)</span></span><br><span class="line"><span class="comment"># print('第三次；', res3)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># low方法+客户端的睡眠</span></span><br><span class="line">res1 = conn.recv(<span class="number">1024</span>)</span><br><span class="line">print(<span class="string">'第一次；'</span>, res1)</span><br><span class="line"></span><br><span class="line">res2 = conn.recv(<span class="number">1024</span>)</span><br><span class="line">print(<span class="string">'第二次；'</span>, res2)</span><br><span class="line"></span><br><span class="line">res3 = conn.recv(<span class="number">1024</span>)</span><br><span class="line">print(<span class="string">'第三次；'</span>, res3)</span><br></pre></td></tr></table></figure>

<h2 id="4-2-客户端"><a href="#4-2-客户端" class="headerlink" title="4.2 客户端"></a>4.2 客户端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">Copyfrom socket <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">client = socket(AF_INET, SOCK_STREAM)</span><br><span class="line">client.connect((<span class="string">'127.0.0.1'</span>, <span class="number">8080</span>))</span><br><span class="line"></span><br><span class="line">client.send(<span class="string">b'hello'</span>)</span><br><span class="line">client.send(<span class="string">b'world'</span>)</span><br><span class="line">client.send(<span class="string">b'lqz'</span>)</span><br><span class="line"><span class="comment"># 服务端收到b'helloworldlqz'</span></span><br><span class="line"></span><br><span class="line">client.send(<span class="string">b'hello'</span>)</span><br><span class="line">time.sleep(<span class="number">0.2</span>)</span><br><span class="line"><span class="comment"># 服务端收到b'hello'</span></span><br><span class="line"></span><br><span class="line">client.send(<span class="string">b'world'</span>)</span><br><span class="line">time.sleep(<span class="number">0.2</span>)</span><br><span class="line"><span class="comment"># 服务端收到b'world'</span></span><br><span class="line"></span><br><span class="line">client.send(<span class="string">b'lqz'</span>)</span><br><span class="line"><span class="comment"># 服务端收到b'lqz'</span></span><br></pre></td></tr></table></figure>

<p>2.接收方不及时接收缓冲区的包，造成多个包接收（客户端发送了一段数据，服务端只收了一小部分，服务端下次再收的时候还是从缓冲区拿上次遗留的数据，产生粘包）</p>
<h2 id="4-3-服务端"><a href="#4-3-服务端" class="headerlink" title="4.3 服务端"></a>4.3 服务端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># _*_coding:utf-8_*_</span></span><br><span class="line">__author__ = <span class="string">'lqz'</span></span><br><span class="line"><span class="keyword">from</span> socket <span class="keyword">import</span> *</span><br><span class="line">ip_port = (<span class="string">'127.0.0.1'</span>, <span class="number">8080</span>)</span><br><span class="line"></span><br><span class="line">TCP_socket_server = socket(AF_INET, SOCK_STREAM)</span><br><span class="line">TCP_socket_server.bind(ip_port)</span><br><span class="line">TCP_socket_server.listen(<span class="number">5</span>)</span><br><span class="line"></span><br><span class="line">conn, addr = TCP_socket_server.accept()</span><br><span class="line"></span><br><span class="line">data1 = conn.recv(<span class="number">2</span>)  <span class="comment"># 一次没有收完整</span></span><br><span class="line">data2 = conn.recv(<span class="number">10</span>)  <span class="comment"># 下次收的时候,会先取旧的数据,然后取新的</span></span><br><span class="line"></span><br><span class="line">print(<span class="string">'-----&gt;'</span>, data1.decode(<span class="string">'utf-8'</span>))</span><br><span class="line">print(<span class="string">'-----&gt;'</span>, data2.decode(<span class="string">'utf-8'</span>))</span><br><span class="line"></span><br><span class="line">conn.close()</span><br></pre></td></tr></table></figure>

<h2 id="4-4-客户端"><a href="#4-4-客户端" class="headerlink" title="4.4 客户端"></a>4.4 客户端</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># _*_coding:utf-8_*_</span></span><br><span class="line">__author__ = <span class="string">'lqzlqz'</span></span><br><span class="line"><span class="keyword">import</span> socket</span><br><span class="line">BUFSIZE = <span class="number">1024</span></span><br><span class="line">ip_port = (<span class="string">'127.0.0.1'</span>, <span class="number">8080</span>)</span><br><span class="line"></span><br><span class="line">s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</span><br><span class="line">res = s.connect_ex(ip_port)</span><br><span class="line"></span><br><span class="line">s.send(<span class="string">'hello feng'</span>.encode(<span class="string">'utf-8'</span>))</span><br></pre></td></tr></table></figure></section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/6-Socket%E6%8A%BD%E8%B1%A1%E5%B1%82/">
        <span class="nav-arrow">← </span>
        
          python/网络编程/6-Socket抽象层
        
      </a>
    
    
      <a class="nav-right" href="/python/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/10-%E5%9F%BA%E4%BA%8EUDP%E5%8D%8F%E8%AE%AE%E7%9A%84socket%E5%A5%97%E6%8E%A5%E5%AD%97%E7%BC%96%E7%A8%8B/">
        
          python/网络编程/10-基于UDP协议的socket套接字编程
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#一、解决粘包问题-low版"><span class="toc-nav-text">一、解决粘包问题(low版)</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-1-服务端"><span class="toc-nav-text">1.1 服务端</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-2-客户端"><span class="toc-nav-text">1.2 客户端</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-3-为何low"><span class="toc-nav-text">1.3 为何low</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#二、补充struct模块"><span class="toc-nav-text">二、补充struct模块</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-1-简单使用"><span class="toc-nav-text">2.1 简单使用</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#三、解决粘包问题"><span class="toc-nav-text">三、解决粘包问题</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-1-使用struct模块创建报头"><span class="toc-nav-text">3.1 使用struct模块创建报头</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-2-服务端"><span class="toc-nav-text">3.2 服务端</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-3-客户端"><span class="toc-nav-text">3.3 客户端</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#四、TCP协议粘包问题分析"><span class="toc-nav-text">四、TCP协议粘包问题分析</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-1-服务端"><span class="toc-nav-text">4.1 服务端</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-2-客户端"><span class="toc-nav-text">4.2 客户端</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-3-服务端"><span class="toc-nav-text">4.3 服务端</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-4-客户端"><span class="toc-nav-text">4.4 客户端</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/网络编程/9-解决粘包问题/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/网络编程/9-解决粘包问题",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>